package j19.exception;

import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * 这是一个关于输入的工具类
 * 当然在这里,对输入的异常进行了简单的处理
 */
public class InputUtil {
	
	/**
	 * 按照正则表达式判断输入信息格式
	 * @param tishi		输入提示
	 * @param regex		正则表达式
	 * @param errorTiShi	错误提示
	 * @return
	 */
	public static String getStringCheck(String tishi,String regex,String errorTiShi){
		while(true){
			String demo=InputUtil.getString(tishi);
			if(!demo.matches(regex)){
				System.out.println(errorTiShi);
				continue;
			}
			return demo;
		}
	}
	
	public static String getString(String tishi){
		System.out.print(tishi);
		return new Scanner(System.in).next();	//这里scanner没关闭
	}
	
	/**
	 * @param regex		 正则表达式
	 * @throws Exception	errorTishi
	 */
	public static String getString
					(String tishi,String regex,String errorTiShi) throws Exception{
		Scanner input=new Scanner(System.in);
		System.out.print(tishi);
		String answer= input.next();
		if(!answer.matches(regex)){
			throw new Exception(errorTiShi);
		}
		return answer;
	}
	
	
	
	public static int getIntBasic(String tishi,int min) 
			throws InputMismatchException,Exception{
		int num=getIntBasic( tishi);
		if(num<min)
		{
			throw new Exception("数字必须大于"+min);
		}
		return num;
	}
	
	
	public static int getIntBasic(String tishi,int begin,int end) 
						throws InputMismatchException,Exception{
		int num=getIntBasic( tishi);
		if(!(num>=begin&&num<=end)){
			throw new Exception("数字范围错误");
		}
		return num;
	}
	
	public static int getIntAdvanced(String tishi, int begin, int end) {
		do {
			try {
				return getIntBasic(tishi, begin, end);
			} catch (InputMismatchException e) {
				System.out.println("输入必须是数字!");
			} catch (Exception e) {
				System.out.println("输入数字错误!" + e.getMessage());
			}
		} while (true);
	}
	
	
	
	public static int getIntAdvanced(String tishi) {
		do {
			try {
				return getIntBasic(tishi);
			} catch (Exception e) {
				System.out.println("输入数字错误!");
			}
		} while (true);
	}

	public static int getIntBasic(String tishi) throws InputMismatchException{
		System.out.print(tishi);
		Scanner scanner = new Scanner(System.in);
		int answer = scanner.nextInt();
		scanner.close();
		return answer;
	}
	
}
